package com.kingone.springboottest.controller;

import com.kingone.springboottest.entity.Book;
import com.kingone.springboottest.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //使用restful风格的controller注解，可以省去@ReposeBody注解
@RequestMapping("/book")
public class BookHandler {

    @Autowired
    private BookRepository bookRepository;   //其中含有数据操作对象

    @GetMapping("/findAll")
    public List<Book> findAll(){
        return bookRepository.findAll();
    }

    @GetMapping("/findAllByPage/{page}/{size}")
    /*完成分页查找操作。注意：此处的page是从0开始的，与我们的分页数相差1；
    * 因此在我们获取到分页数时，需要进行减1操作。*/
    public Page<Book> findAllByPage(@PathVariable("page") Integer page,
                                    @PathVariable("size") Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return bookRepository.findAll(pageable);
    }

    @PostMapping("/save")       /*此处为提交请求。*/
    public String save(@RequestBody  Book book){
        Book result = bookRepository.save(book);
        if(result !=null){
            return "success";   /*此处的return为向前端返回的数据data*/
        } else {
            return "error";
        }
    }

    @GetMapping("/findById/{id}")
    public Book findById(@PathVariable("id") Integer id){
        return bookRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Book book){
        Book result = bookRepository.save(book);
        if(result !=null){
            return "success";
        } else {
            return "error";
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id")Integer id){
        bookRepository.deleteById(id);
    }
}
